package com.jch.dm7_thread_pool.example;

import org.apache.log4j.Logger;

import java.util.concurrent.*;

public class ThreadPoolDeadLockAvoidance {

    private static final Logger log = Logger.getLogger(ThreadPoolDeadLockAvoidance.class);

    private final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1,
            // 最大线程池大小
            1,
            60, TimeUnit.SECONDS,
            // 工作队列
            new SynchronousQueue<Runnable>(),
            // 线程池饱和处理策略
            new ThreadPoolExecutor.CallerRunsPolicy());

    public static void main(String[] args) {
        ThreadPoolDeadLockAvoidance me = new ThreadPoolDeadLockAvoidance();
        me.test("<This will NOT deadlock>");
    }

    public void test(final String msg){
        Runnable taskA = new Runnable() {
            @Override
            public void run() {
                log.info("Executing TaskA...");
                Runnable taskB = new Runnable() {
                    @Override
                    public void run() {
                        log.info("TaskB processes " + msg);
                    }
                };
                Future<?> result = threadPoolExecutor.submit(taskB);
                try {
                    // 等待TaskB执行结束才能继续执行TaskA,使TaskA和TaskB成为有依赖关系的两个任务
                    result.get();
                } catch (InterruptedException | ExecutionException e) {
                    e.printStackTrace();
                }
                log.info("TaskA Done.");
            }
        };
        threadPoolExecutor.submit(taskA);
    }

}
